<?php


namespace app\api\controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use app\api\model\OcrInfoModel;
use app\api\model\YunXinModel;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\api\model\FragmentModel;
use app\api\validate\LoginValidate;
use library\File;
use think\facade\Cache;


class Pub extends ApiBase
{

    /**
     * 上传图片
     *
     */
    public function uploadImg(){

        $params = input();
        $file = $this->request->file('file');
        $name = $file->getInfo()['name'];
        $index = strripos($file->getInfo()['name'],'.');
        $suffix = substr($file->getInfo()['name'],$index+1);
        $imgs = ['bmp','jpg','png','jpeg','tif','gif','pcx','tga','exif','fpx','svg','psd','webp','avif','apng','WMF','raw'];
        $vodeos = ['mp4','3gp','wmv','mov','m4v','rm','rmvb','asf','asx'];
        if(in_array($suffix,$imgs)){
            $folder = 'IMAGES/'.date('Y-m-d',time()).'/';
        }elseif(in_array($suffix,$vodeos)){

            $folder = 'IVIDEOS/'.date('Y-m-d',time()).'/';
        }else{

            $folder = 'FILES/';
        }
        $info = File::instance('oss')->save(date('Ymd',time()) .'/'.$folder.$name, file_get_contents($file->getRealPath()));
        if (is_array($info) && isset($info['url'])) {

            $ocr_url = '';
            $words = '';
            if (isset($params['ocr']) && $params['ocr'] == 'ocr'){

                $ocr = new Ocr();
                $res = $ocr->ocr($info['url']);
                if ($res){

                    $ocr_url = $res['ocr_url'];
                    $words = $res['words'];
                }else{

                    $this->fail('文件处理失败，请稍候再试！');
                }
            }

            $data['words'] = $words;
            $data['ocr_url'] = $ocr_url;
            $data['url'] = $info['url'];

            if (isset($params['meeting_id']) && !empty($params['meeting_id'])){
                $ocr = [

                    'meeting_id'=>$params['meeting_id'],
                    'ocr_info'=>$data,
                ];
                OcrInfoModel::ocrInfoAdd($ocr);
            }
            $this->successful('上传成功',$data);
        } else {

            $this->fail('文件处理失败，请稍候再试！');
        }

    }

    /**
     *
     * 碎片管理信息
     */
    public function info(){

        $data = FragmentModel::info(input('id'));
        $this->successful('查询成功',$data);
    }

    public function createClient(){
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => 'LTAI5tFWUhmS17x4mr7dRiWQ',
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => 'e1AlwaHSTdkAZYGpC1wVAmU7ZNeVUP'
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     *
     * 发送验证码
     */
    public function sendCode(LoginValidate $request){
        $params = $this->request->post();
//        if (!$request->scene('sendCode')->check($params)){
//
//            $this->fail($request->getError());
//        }
        $code = mt_rand(100000,999999);
        $templateParam = ['code' => $code]; // 验证码
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $params['phone'],
            "signName" => '码谷重庆信息科技有限公司',
            "templateCode" => "SMS_468670029",
            "templateParam" => json_encode($templateParam)
        ]);
        $runtime = new RuntimeOptions([]);
        //try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            if ($res->body->code == "OK"){

                Cache::set($params['phone'],$code,180);
                $this->successful('发送验证码成功',$code);
            }else{

                $this->fail($res->body->message);
            }
        //}
//        catch (Exception $error) {
//            if (!($error instanceof TeaError)) {
//                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
//            }
//            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
//            // 错误 message
////            var_dump($error->message);
////            // 诊断地址
////            var_dump($error->data["Recommend"]);
////            Utils::assertAsString($error->message);
//           // $this->fail($error->getMessage());
//        }
    }



    public function test(){
//
//        $data = [
//
//            'model'=>'Qwen/Qwen1.5-7B-Chat-GGUF',
//            'messages'=>[
//
//                [
//                    'role'=>'user',
//                    'content'=>'太阳离地球有多远的距离？',
//                ]
//            ]
//        ];
//
//        $data = postJsonCurl($data,'http://localhost:1234/v1/chat/completions',1);
//        halt($data);
//        $res = YunXinModel::createMeeting(1);
//        halt($res);
        // 定义关键字数组
        $keywords = [
            "姓名", "科室", "病房", "住院天数", "入院日期", "过敏情况", "治疗转归", "自动出院", "出院记录",
            "入院诊断", "病理诊断", "出院诊断", "入院情况", "主要治疗", "主要检查结果", "手术名称及术中主要所见",
            "出院情况", "查体", "出院医嘱", "临床诊断", "简要病史", "检查所见", "检查结论", "检查项目", "检查方式",
            "结果解释", "超声所见", "超声提示", "病理检查及所见", "检查参数", "印象", "镜检诊断", "标本名称",
            "肿瘤部位", "肿瘤答题类别", "肿瘤大小", "组织学类型", "组织学分级", "淋巴结转移情况", "大体描述",
            "镜下所见", "检查方法", "检查提示", "诊断意见", "病理学诊断", "出院时情况", "出院后用药及建议",
            "检查名称", "影像表现", "检测项目", "送检材料", "检测方法", "试剂信息", "疾病描述", "检测结果",
            "肉眼所见", "光镜所见", "病理诊断", "临床诊断", "标本类型", "标本评估", "检测位点", "对照来源",
            "结果描述", "所见", "影像所见", "影像诊断", "主诉", "现病史", "既往史", "个人史", "婚育史",
            "家族史", "体格检查", "专科情况", "主要诊疗措施", "出院医嘱", "基因突变分析结果", "入院情况",
            "化验室检查", "诊治经过", "月经及婚育史", "辅助检查", "治疗经过", "重要检查结果"
        ];

// 定义输入文本
        $input_text = "绍兴文理学院附属医院\n\t\n\t(绍兴市立医院)\n\t\n\t患者姓名杨永华科别呼吸与危重症医学科一床号\n\t\n\t1540住院号6195078\n\t\n\t出院记录\n\t\n\t入院日期：2024-03-2909：30\n\t\n\t出院日期：2024-04-1814：00\n\t\n\t入院诊断：恶性肿瘤化学治疗后的随出院诊断：\n\t\n\t右肺鳞癌(T2N3M0Ic期)】\n\t\n\t诊检查\n\t\n\t阻塞性肺炎\n\t\n\t右肺鳞癌(cT2NOM0IB期)\n\t\n\t肺恶性肿瘤维持性化学治\n\t\n\t左下肺鳞癌术后(pT3NOM0\n\t\n\t疗\n\t\n\tIIA期)\n\t\n\t肺恶性肿瘤免疫治疗\n\t\n\t原发性高血压\n\t\n\t慢性阻塞性肺病伴有急性\n\t\n\t2型糖尿病\n\t\n\t加重(G0LD3级，E组)\n\t\n\t2型糖尿病\n\t\n\t原发性高血压\n\t\n\t房性期前收缩[房性早搏]\n\t\n\t室性期前收缩\n\t\n\t肝囊肿\n\t\n\t颈淋巴结肿大\n\t\n\tI度房室传导阻滞\n\t\n\t住院天数：20天\n\t\n\t入院情况：\n\t\n\t1.患者男，76岁，因“确诊肺癌4年余\n\t\n\t废血2月”入院。2.\n\t\n\t查体：患者有高血压及糖尿病病史。3.查体\n\t\n\t未及明显千湿\n\t\n\t罗音，双下肢可见水肿；4.辅助检查：既往屙部墙强CT焱\n\t\n\t生肺术后改变，\n\t\n\t两肺慢性支气管病变，两侧肺气肿，两肺多发间质性病\n\t\n\t诊疗经过：\n\t\n\t患者入院后积极完善相关辅助检查，2024-03-29，CT胸部平扫及增强(\n\t\n\t16/64排)：1.左肺术后改变。2.右肺上叶条片影，对照前片2023-04-14为新\n\t\n\t发病变，考虑恶性。两侧肺门及纵隔淋巴结肿大。3两肺慢性支气管病变，\n\t\n\t两侧肺气肿，两肺多发间质性病变，炎症伴纤维化考虑，建议定期复查。4.\n\t\n\t两侧多发钙化灶，增殖灶、纤维灶。两侧胸膜增厚、粘连，左侧胸腔少量积\n\t\n\t液。附见：肝内外胆管扩张、左肾囊肿。2024-03-30，心脏：左室舒张功能\n\t\n\t第页\n\t\n\t总页\n\t\n\t";

// 分段识别并处理
        $lines = explode("\n\t\n\t", $input_text);
        $output = '';
        $keyword = '';

        foreach ($lines as $line) {
            // 检测关键字
            foreach ($keywords as $kw) {
                if (strpos($line, $kw) !== false) {
                    $keyword = $kw;
                    break;
                }
            }

            // 处理 \n\t\n\t 符号
            $line = preg_replace('/\n\t\n\t/', "\n", $line);

            // 根据规则3和规则4进一步处理
            $line = preg_replace_callback('/\n\t\n\t(.)/u', function ($matches) use ($keywords) {
                if (!in_array($matches[1], $keywords) && !is_numeric($matches[1])) {
                    return $matches[1];
                }
                return "\n" . $matches[1];
            }, $line);

            // 将当前行附加到输出
            $output .= $line . "\n";
        }

// 按关键字分类
        $categorized_output = [];
        $current_category = '未分类';

        foreach (explode("\n", $output) as $line) {

            foreach ($keywords as $kw) {
                if (strpos($line, $kw) !== false) {
                    $current_category = $kw;
                    if (!isset($categorized_output[$current_category])) {
                        $categorized_output[$current_category] = '';
                    }
                    break;
                }
            }
            $categorized_output[$current_category] .= $line . "\n";
        }

// 输出分类结果
        foreach ($categorized_output as $category => $text) {
            echo "【{$category}】\n";
            echo $text . "\n";
        }
    }




}